#include "switch_mode.h"
#include "relay_ctrl.h"
#include "pir_sensor_detect.h"
#include "key.h"

typedef enum
{
    SWITCH_STATE_INIT,
    SWITCH_STATE_DET,
    SWITCH_STATE_ON,
    SWITCH_STATE_OFF,
} switch_state_e;

static struct
{
    switch_state_e state;
    relay_state_e relay_state;
} switch_mode_ctx;

void switch_mode_init(void)
{
    switch_mode_ctx.state = SWITCH_STATE_INIT;
    switch_mode_ctx.relay_state = RELAY_OFF;
}

void switch_mode_state_deinit(void)
{
    switch_mode_ctx.state = SWITCH_STATE_INIT;
}

void switch_mode_task(void)
{
    switch (switch_mode_ctx.state)
    {
    case SWITCH_STATE_INIT:
        pir_sensor_set_status(PIR_SENSOR_DISABLED);
        switch_mode_ctx.state = SWITCH_STATE_DET;
        break;
    case SWITCH_STATE_DET:
        switch_mode_ctx.relay_state = get_relay_sw();
        if (switch_mode_ctx.relay_state == RELAY_ON)
        {
            switch_mode_ctx.state = SWITCH_STATE_ON;
        }
        else if (switch_mode_ctx.relay_state == RELAY_OFF)
        {
            switch_mode_ctx.state = SWITCH_STATE_OFF;
        }
        break;
    case SWITCH_STATE_ON:
        if (is_key_click())
        {
            set_relay_sw(RELAY_OFF);
            switch_mode_ctx.state = SWITCH_STATE_DET;
        }
        break;
    case SWITCH_STATE_OFF:
        if (is_key_click())
        {
            set_relay_sw(RELAY_ON);
            switch_mode_ctx.state = SWITCH_STATE_DET;
        }
        break;

    default:
        break;
    }
}
